package com.winit.agent.manager;

import com.winit.agent.constants.IdTag;
import com.winit.agent.model.Agent;
import com.winit.agent.repository.AgentRepository;
import com.winit.agent.repository.IAgentRepositoryExt;
import com.winit.common.base.bean.ExecuteResult;
import com.winit.common.base.web.BaseController;
import com.winit.commons.util.SeqGenerate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class AgentManager {

    private static Logger log = LoggerFactory.getLogger(AgentManager.class);

    @Autowired
    private AgentRepository agentRepository;
    @Autowired
    private IAgentRepositoryExt agentRepositoryExt;

    public ExecuteResult getAgent(String agentId, String agentIp){
        ExecuteResult executeResult = new ExecuteResult();
        executeResult.setData(this.agentRepository.findByAgentIdAndAgentIp(agentId, agentIp));
        return executeResult;
    }

    public ExecuteResult updateAgent(Agent agent){
        ExecuteResult executeResult = new ExecuteResult();
        if (StringUtils.isEmpty(agent.getAgentId())){
            log.info("agenId is null, add will be executed.");
            agent.setAgentId(SeqGenerate.createId(IdTag.AGENT_ID));
            this.agentRepository.save(agent);
            executeResult.setData(agent.getAgentId());
            return executeResult;
        }
        if (!this.agentRepositoryExt.updateByIdForPropertyNotNull(agent)){
            executeResult.setCode(BaseController.REQUEST_ERROR);
            executeResult.setDesc("no item updated.");
        }
        return executeResult;
    }

    public ExecuteResult operateAgent(String agentId, Integer operation){
        ExecuteResult executeResult = new ExecuteResult();
        if (1 == operation.intValue()){
            this.agentRepository.delete(agentId);
        }else {
            executeResult.setCode(BaseController.REQUEST_ERROR);
            executeResult.setDesc("operation not supported");
        }
        return executeResult;
    }
}
